<template>
  <div class="add">
    <el-card class="add-container">
      <el-form :model="state.questionForm" :rules="state.rules" ref="questionRef" label-width="100px" class="questionForm">
        <el-form-item label="文章类型">
          <el-select v-model="state.questionForm.moduleCode" filterable placeholder="Select" style="width: 300px">
            <el-option v-for="item in state.modules" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="文章标题" prop="title">
          <el-input style="width: 300px" type="textarea" v-model="state.questionForm.title" placeholder="请输入商品简介(100字)"></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-input style="width: 300px" v-model="state.questionForm.tag" placeholder="请输入商品小标签"></el-input>
        </el-form-item>
        <el-form-item label="是否展示" prop="isShow">
          <el-radio-group v-model="state.questionForm.isShow">
            <el-radio label="0">展示</el-radio>
            <el-radio label="1">不展示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item required label="封面图片" prop="coverPicture">
          <el-upload class="avatar-uploader"
            :action="state.uploadImgServer" accept="jpg,jpeg,png"
            :headers="{token: state.token}"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :on-success="handleUrlSuccess">
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="state.questionForm.coverPicture" :src="state.questionForm.coverPicture" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="答案">
          <div ref='editor'></div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd()">{{ state.id ? '立即修改' : '立即创建' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import WangEditor from 'wangeditor'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { localGet, uploadImgServer } from '@/utils'

const { proxy } = getCurrentInstance()
const editor = ref(null)
const questionRef = ref(null)
const route = useRoute()
const router = useRouter()
const { id } = route.query
const state = reactive({
  uploadImgServer,
  token: localGet('token') || '',
  id: id,
  type: 'add', // 操作类型
  questionForm: {
    title: '',
    isShow: '0',
    coverPicture: '',
    tag: '',
    moduleCode: '',
  },
  rules: {
    title: [
      { required: 'true', message: '请填写商品名称', trigger: ['change'] }
    ]
  },
  modules: [],
})

let instance
onMounted(() => {
  instance = new WangEditor(editor.value)
  instance.config.showLinkImg = false
  instance.config.showLinkImgAlt = false
  instance.config.showLinkImgHref = false
  instance.create()
  axios.post('api/admin/module/v1/list', {
    loginUserName: localGet('token').username
  }).then(res=>{
    state.modules = res.map(item => {
      return {
        value: item.moduleCode,
        label: item.moduleName
      }
    })
  })
  if (id) {
    state.type = 'edit';
    axios.post('api/admin/question/v1/detail', {
      questionId: id
    }).then(res=>{
      console.log("res.enable"+res.enable)
      state.questionForm.moduleCode = res.moduleCode,
      state.questionForm.coverPicture = res.coverPicture,
      state.questionForm.title = res.title,
      state.questionForm.tag = res.tag
      state.questionForm.isShow = String(res.enable)
      if (instance) {
        // 初始化商品详情 html
        instance.txt.html(res.answer)
      }
    })
  }
})
onBeforeUnmount(() => {
  instance.destroy()
  instance = null
})
const submitAdd = () => {
  questionRef.value.validate((vaild) => {
    if (vaild) {
      // 默认新增用 post 方法
      let httpOption = axios.post
      let subTitle = instance.txt.text();
      if (subTitle && subTitle.length > 20){
        subTitle = subTitle.substring(0,20);
      }
      let params = {
        moduleCode: state.questionForm.moduleCode,
        coverPicture: state.questionForm.coverPicture,
        answer: instance.txt.html(),
        title: state.questionForm.title,
        enable: state.questionForm.isShow,
        tag: state.questionForm.tag,
        subTitle: subTitle
      }
      console.log('params', params)
      let url = '/api/admin/question/v1/create';
      if (id) {
        params.id = id
        url = '/api/admin/question/v1/update';
      }
      httpOption(url, params).then(() => {
        ElMessage.success(id ? '修改成功' : '添加成功')
        router.push({ path: '/question' })
      })
    }
  })
}
const handleBeforeUpload = (file) => {
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
const handleUrlSuccess = (val) => {
  state.questionForm.coverPicture = proxy.$filters.prefix(val.data.url) || ''
}
const handleChangeCate = (val) => {
  state.moduleCode = val[2] || 0
}
</script>

<style scoped>
  .add {
    display: flex;
  }
  .add-container {
    flex: 1;
    height: 100%;
  }
  .avatar-uploader {
    width: 100px;
    height: 100px;
    color: #ddd;
    font-size: 30px;
  }
  .avatar-uploader-icon {
    display: block;
    width: 100%;
    height: 100%;
    border: 1px solid #e9e9e9;
    padding: 32px 17px;
  }
</style>
